//
//  QuestionViewController.m
//  VoiceClass
//
//  Created by caoxiaobo on 2018/1/1.
//  Copyright © 2018年 YRX. All rights reserved.
//

#import "QuestionViewController.h"
#import "IALessonViewController.h"
#import "AddQuestionViewController.h"
#import "BrowseResultViewController.h"
#import "UIView+Extension.h"
#import "IASubjectItem.h"
#import "IAStudent.h"
#import "IAMetaDataReader.h"
#import "IAQuestionListCell.h"
#import "MBProgressHUD.h"
#import "Definition.h"

static NSString * const IAQuestionCellID = @"IAQuestionCellID";

@interface QuestionViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSString *subjectName;
@property (nonatomic, strong) NSArray <IAQuestionListItem *> * items;
@property (nonatomic, strong) NSArray <IASubjectItem *> * subjects;
@property (nonatomic, strong) IAStudent * suggestStudent;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UILabel *msgLabel;

@end

@implementation QuestionViewController

-(instancetype)initWithSubjectName:(NSString *)subjectName subjects:(NSArray <IASubjectItem *> *)subjects {
    self = [super init];
    if (self) {
        _subjectName = subjectName ? : @"";
        _subjects = subjects;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CGFloat tabBarH = 0.0f;
    if (self.subjects.count > 0) {
        self.title = [NSString stringWithFormat:@"%@问题列表(%@)", self.subjectName, @( self.subjects.count)];
        tabBarH = 46.0f;
        CGRect tabBarRect = CGRectMake(0, self.view.cHeight - tabBarH, self.view.cWidth, tabBarH);
        UIButton *tabBar = [[UIButton alloc] initWithFrame:tabBarRect];
        [tabBar setTitle:@"查看答题结果" forState:UIControlStateNormal];
        [tabBar addTarget:self action:@selector(browseResult) forControlEvents:UIControlEventTouchUpInside];
        tabBar.backgroundColor = HEXCOLOR(0x42A8FF);
        [self.view addSubview:tabBar];
    } else {
        self.title = [NSString stringWithFormat:@"%@问题列表", self.subjectName];
    }
    
    UIBarButtonItem *backItem=[[UIBarButtonItem alloc]init];
    backItem.title=@"返回";
    self.navigationItem.backBarButtonItem = backItem;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"新增问题" style:UIBarButtonItemStylePlain target:self action:@selector(addQuestion)];
    _tableView = [[UITableView alloc] init];
    _tableView.frame = CGRectMake(0, 0, self.view.cWidth, self.view.cHeight - tabBarH);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[IAQuestionListCell class] forCellReuseIdentifier:IAQuestionCellID];
    [self.view addSubview:_tableView];
    [self uplateAndReloadTabelView];
}

- (void)uplateAndReloadTabelView {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableDictionary *countDictionary = [NSMutableDictionary dictionary];
        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:self.subjects.count];
        NSArray *students = [IAMetaDataReader getStudents];
        [self.subjects enumerateObjectsUsingBlock:^(IASubjectItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            IAQuestionListItem *item = [IAQuestionListItem new];
            item.students = students;
            item.subjectItem = obj;
            NSMutableArray *studentNames = [NSMutableArray arrayWithCapacity:students.count];
            for (IAStudent *student in students) {
                if (student.name) {
                    [studentNames addObject:student.name];
                }
            }
            item.names = [studentNames copy];
            NSMutableArray *rates = [NSMutableArray arrayWithCapacity:studentNames.count];
            NSArray *results = [IAMetaDataReader getSubjectResultsOfQuestion:obj.question];
            for (IAStudent *student in students) {
                CGFloat goal = 0;
                NSInteger count = 0;
                if (countDictionary[student.stuID]) {
                    count = [countDictionary[student.stuID] integerValue];
                } else {
                    countDictionary[student.stuID] = @(count);
                }
                for (IASubjectAnswerResult *result in results) {
                    if (result.goal &&
                        [student.stuID isEqualToString:result.student.stuID]) {
                        count += 1;
                        if ([result.goal floatValue] > goal) { // 取每个学生分数的最高一次
                            goal = [result.goal floatValue];
                        }
                    }
                }
                countDictionary[student.stuID] = @(count);
                [rates addObject:@(goal)];
            }
            
            item.rates = [rates copy];
            [mutableArray addObject:item];
        }];
        
        IAStudent *suggestStudent = nil;
        NSArray *keys = countDictionary.allKeys;
        if (keys.count > 0) {
            NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                NSNumber *number1 = countDictionary[obj1];
                NSNumber *number2 = countDictionary[obj2];
                return [number1 compare:number2];
            }];
            NSString *suggestStudentID = [sortedKeys firstObject];
            if (suggestStudentID) {
                for (IAStudent *student in students) {
                    if ([student.stuID isEqualToString:suggestStudentID]) {
                        suggestStudent = student;
                    }
                }
            }
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.suggestStudent = suggestStudent;
            self.items = [mutableArray copy];
            [self.tableView reloadData];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
    });
}

- (void)browseResult {
    BrowseResultViewController *browseController = [[BrowseResultViewController alloc] initWithSubjectName:self.subjectName];
    [self.navigationController pushViewController:browseController animated:YES];
}

- (void)addQuestion {
    AddQuestionViewController *addQuestionController = [[AddQuestionViewController alloc] initWithSubjectName:self.subjectName];
    addQuestionController.completionBlock = ^{
        [IAMetaDataReader getSubjectItemsForName:self.subjectName completion:^(id obj) {
            NSMutableArray *mutableArray = [NSMutableArray array];
            [obj enumerateObjectsUsingBlock:^(IASubjectItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                IAQuestionListItem *item = [IAQuestionListItem new];
                item.subjectItem = obj;
                [mutableArray addObject:item];
            }];
            self.subjects = mutableArray;
            [self.tableView reloadData];
        }];
    };
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:addQuestionController];
    [self presentViewController:navController animated:YES completion:nil];
}

- (UILabel *)msgLabel {
    if (!_msgLabel) {
        _msgLabel = [[UILabel alloc] init];
        _msgLabel.text = @"暂时没有问题";
        _msgLabel.frame = CGRectMake(0, 0, self.tableView.cWidth, self.tableView.cHeight * 0.6);
        _msgLabel.font = [UIFont boldSystemFontOfSize:18.0f];
        _msgLabel.textColor = [UIColor lightGrayColor];
        _msgLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _msgLabel;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = self.subjects.count;
    if (count == 0) {
        [tableView addSubview:self.msgLabel];
    } else {
        [self.msgLabel removeFromSuperview];
    }
    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    IAQuestionListItem *item = self.items[indexPath.row];
    return item.cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IAQuestionListCell *cell = [tableView dequeueReusableCellWithIdentifier:IAQuestionCellID];
    if (!cell) {
        cell = [[IAQuestionListCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:IAQuestionCellID];
    }
    IAQuestionListItem *item = self.items[indexPath.row];
    cell.item = item;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    IAQuestionListItem *listItem = self.items[indexPath.row];
    IASubjectItem *item = listItem.subjectItem;
    IALessonViewController *lessonController = [[IALessonViewController alloc] init];
    lessonController.subject = item;
    lessonController.resultDidUpdateBlock = ^{
        [self uplateAndReloadTabelView];
    };
    
    if (self.suggestStudent) {
        lessonController.suggestStudent = self.suggestStudent;
    }
    
    [self.navigationController pushViewController:lessonController animated:YES];
}

@end
